﻿using Dapper;
using JX.Core;
using JX.Core.Entity;
using JX.Dapper;
using JX.Infrastructure;
using JX.Infrastructure.Common;
using JX.Infrastructure.Framework;
using JX.Infrastructure.Log;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace JX.Application
{
	public partial class UsersServiceAppDapper : ServiceAppDapper<UsersEntity>, IUsersServiceAppDapper
	{
		#region 仓储接口
		private readonly IUnitOfWorkFactory _uowFactory;
		private readonly IUserMoneyServiceAppDapper _userMoneyServiceApp;
		private readonly IUserExpServiceAppDapper _userExpServiceApp;
		private readonly IUserPointServiceAppDapper _userPointServiceApp;
		private readonly IUserValidDateServiceAppDapper _userValidDateServiceApp;
		private readonly IUserGroupsServiceAppDapper _userGroupsServiceApp;
		private readonly IModelsServiceAppDapper _ModelsServiceApp;
		private readonly IValidLogRepositoryDapper _validLogRepository;
		private readonly IPointLogRepositoryDapper _pointLogRepository;
		private readonly IExpLogRepositoryDapper _expLogRepository;
		private readonly IContacterRepositoryDapper _contacterRepository;
		private readonly IFavoriteRepositoryDapper _favoriteRepository;
		private readonly IFriendRepositoryDapper _friendRepository;
		private readonly ILogRepositoryDapper _LogRepository;
		/// <summary>
		/// 仓储接口
		/// </summary>
		/// <param name="repository"></param>
		/// <param name="validLogRepository"></param>
		/// <param name="pointLogRepository"></param>
		/// <param name="expLogRepository"></param>
		/// <param name="contacterRepository"></param>
		/// <param name="favoriteRepository"></param>
		/// <param name="friendRepository"></param>
		/// <param name="userGroupsServiceApp"></param>
		/// <param name="ModelsServiceApp"></param>
		/// <param name="userMoneyServiceApp"></param>
		/// <param name="userExpServiceApp"></param>
		/// <param name="userPointServiceApp"></param>
		/// <param name="userValidDateServiceApp"></param>
		/// <param name="logRepository"></param>
		/// <param name="uowFactory"></param>
		public UsersServiceAppDapper(IUsersRepositoryDapper repository,
			IValidLogRepositoryDapper validLogRepository,
			IPointLogRepositoryDapper pointLogRepository,
			IExpLogRepositoryDapper expLogRepository,
			IContacterRepositoryDapper contacterRepository,
			IFavoriteRepositoryDapper favoriteRepository,
			IFriendRepositoryDapper friendRepository,
			IUserGroupsServiceAppDapper userGroupsServiceApp,
			IModelsServiceAppDapper ModelsServiceApp,
			IUserMoneyServiceAppDapper userMoneyServiceApp,
			IUserExpServiceAppDapper userExpServiceApp,
			IUserPointServiceAppDapper userPointServiceApp,
			IUserValidDateServiceAppDapper userValidDateServiceApp,
			ILogRepositoryDapper logRepository,
			IUnitOfWorkFactory uowFactory) : base(repository)
		{
			m_repository = repository;
			_validLogRepository = validLogRepository;
			_pointLogRepository = pointLogRepository;
			_expLogRepository = expLogRepository;
			_contacterRepository = contacterRepository;
			_favoriteRepository = favoriteRepository;
			_friendRepository = friendRepository;
			_userGroupsServiceApp = userGroupsServiceApp;
			_ModelsServiceApp = ModelsServiceApp;
			_userMoneyServiceApp = userMoneyServiceApp;
			_userExpServiceApp = userExpServiceApp;
			_userPointServiceApp = userPointServiceApp;
			_userValidDateServiceApp = userValidDateServiceApp;
			_LogRepository = logRepository;
			_uowFactory = uowFactory;
		}
		#endregion

		#region 得到实体
		/// <summary>
		/// 通过会员名得到会员的实体类
		/// </summary>
		/// <param name="userName"></param>
		/// <returns></returns>
		public UsersEntity GetByUserName(string userName)
		{
			return Get(p => p.UserName == userName);
		}
		#endregion

		#region 登录、退出、修改密码
		/// <summary>
		/// 会员登录
		/// </summary>
		/// <param name="userName"></param>
		/// <param name="password"></param>
		/// <returns></returns>
		public async Task<IdentityResult> Login(string userName, string password)
		{
			string encryptedValue = StringHelper.MD5(password);
			if (password.Length == 32)
			{
				encryptedValue = password;
			}
			var entity = await m_repository.GetAsync(p => p.UserName == userName && p.UserPassword == encryptedValue);
			if (entity == null || entity.UserID <= 0)
			{
				_LogRepository.SaveLog("会员登录失败！用户名：" + userName, "输入的用户名或密码不正确", userName, LogCategory.LogOnFailure);
				return new IdentityResult("您输入的用户名或密码不正确，请重新输入。");
			}
			switch ((UserStatusEnum)entity.UserStatus)
			{
				case UserStatusEnum.None:
					entity.LoginTimes++;
					entity.LoginTime = new DateTime?(DateTime.Now);
					entity.LoginIP = Utility.GetClientIP();
					entity.LastPassword = DataSecurity.MakeRandomString(10);
					m_repository.Update(entity);
					_LogRepository.SaveLog("会员登录成功！用户名：" + userName, "会员登录成功", userName, LogCategory.LogOnOk);
					return new IdentityResult(CreateClaimsIdentity(entity));
				case UserStatusEnum.Locked:
					_LogRepository.SaveLog("会员登录失败，账号已锁定！用户名：" + userName, "账号已锁定", userName, LogCategory.LogOnFailure);
					return new IdentityResult("账号已锁定。");
				default:
					string logMsg = "会员登录失败，"+EnumHelper.GetDescription((UserStatusEnum)entity.UserStatus) +"！";
					_LogRepository.SaveLog(logMsg + "用户名：" + userName, logMsg, userName, LogCategory.LogOnFailure);
					return new IdentityResult(logMsg);
			}
		}
		/// <summary>
		/// 会员退出
		/// </summary>
		/// <param name="claimsPrincipal"></param>
		/// <returns></returns>
		public bool Logout(ClaimsPrincipal claimsPrincipal)
		{
			var userName = (from c in claimsPrincipal.Claims
						   where c.Type == ClaimTypes.Name
						   select c.Value).FirstOrDefault();
			_LogRepository.SaveLog("会员退出成功！用户名：" + userName, "会员退出成功", userName, LogCategory.LogOff);
			return true;
		}
		/// <summary>
		/// 修改密码
		/// </summary>
		/// <param name="userID"></param>
		/// <param name="oldPwd"></param>
		/// <param name="newPwd"></param>
		/// <returns></returns>
		public async Task<ResultInfo> ModifyPassword(int userID, string oldPwd, string newPwd)
		{
			ResultInfo resultInfo = new ResultInfo();
			if (userID <= 0)
			{
				resultInfo.Msg = "会员不存在！";
				return resultInfo;
			}
			if (string.IsNullOrEmpty(oldPwd))
			{
				resultInfo.Msg = "旧密码不能为空！";
				return resultInfo;
			}
			if (string.IsNullOrEmpty(newPwd))
			{
				resultInfo.Msg = "新密码不能为空！";
				return resultInfo;
			}
			var entity = await m_repository.GetAsync(userID);
			if (entity == null || entity.UserID <= 0)
			{
				resultInfo.Msg = "会员不存在！";
				return resultInfo;
			}
			if (StringHelper.ValidateMD5(StringHelper.MD5(oldPwd), entity.UserPassword))
			{
				entity.UserPassword = StringHelper.MD5(newPwd);
				if (m_repository.Update(entity))
				{
					resultInfo.Status = 1;
					resultInfo.Msg = "修改密码成功！";
				}
				else
				{
					resultInfo.Msg = "修改密码失败！";
				}
				return resultInfo;
			}
			else
			{
				resultInfo.Msg = "您的旧密码不对！";
				return resultInfo;
			}
		}
		#endregion

		#region 得到会员状态
		/// <summary>
		/// 得到会员状态
		/// </summary>
		/// <param name="userID"></param>
		/// <returns></returns>
		public UserStatusEnum GetUserStatus(int userID)
		{
			UserStatusEnum result = UserStatusEnum.NoExist;
			var strResult = m_repository.GetScalar<string>(p => p.UserStatus.ToString(), p => p.UserID == userID);
			if (!string.IsNullOrEmpty(strResult))
			{
				result = (UserStatusEnum)DataConverter.CLng(strResult, 16);
			}
			return result;
		}
		/// <summary>
		/// 得到会员状态
		/// </summary>
		/// <param name="userName"></param>
		/// <returns></returns>
		public UserStatusEnum GetUserStatus(string userName)
		{
			UserStatusEnum result = UserStatusEnum.NoExist;
			string strResult = m_repository.GetScalar<string>(p => p.UserStatus.ToString(), p => p.UserName == userName);
			if (!string.IsNullOrEmpty(strResult))
			{
				result = (UserStatusEnum)DataConverter.CLng(strResult, 16);
			}
			return result;
		}
		#endregion

		#region 添加会员
		/// <summary>
		/// 添加会员、联系人、联系人扩展。
		/// 1、添加会员。
		/// 2、添加联系人，存在相同会员名的联系人则修改。
		/// 3、添加联系人扩展，存在相同会员名的联系人扩展则修改。
		/// </summary>
		/// <param name="usersInfo"></param>
		/// <param name="contacterInfo"></param>
		/// <returns></returns>
		public bool AddUserFull(UsersEntity usersInfo, ContacterEntity contacterInfo)
		{
			bool result = false;
			if(m_repository.Add(usersInfo))
			{
				result = SaveContacter(contacterInfo);
			}
			return result;
		}
		/// <summary>
		/// 添加会员、联系人、联系人扩展。
		/// 1、添加会员。
		/// 2、添加联系人，存在相同会员名的联系人则修改。
		/// 3、添加联系人扩展，存在相同会员名的联系人扩展则修改。
		/// </summary>
		/// <param name="usersInfo"></param>
		/// <param name="contacterInfo"></param>
		/// <returns></returns>
		public async Task<bool> AddUserFullAsync(UsersEntity usersInfo, ContacterEntity contacterInfo)
		{
			bool result = false;
			if (await m_repository.AddAsync(usersInfo))
			{
				result = SaveContacter(contacterInfo);
			}
			return result;
		}
		#endregion

		#region 删除用户及相关权限
		/// <summary>
		/// 删除用户及相关权限
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public bool DelUserFull(int id)
		{
			var user = Get(id);
			if (user == null) return false;
			bool result = false;
			using (var uow = _uowFactory.Create())
			{
				if (m_repository.Delete(id))
				{
					DeleteUserRelation(id,user.UserName);
					result = uow.Commit();
				}
			}
			return result;
		}
		/// <summary>
		/// 删除用户及相关权限
		/// </summary>
		/// <param name="userName"></param>
		/// <returns></returns>
		public bool DelUserFull(string userName)
		{
			var user = Get(p => p.UserName == userName);
			if (user == null) return false;
			bool result = false;
			using (var uow = _uowFactory.Create())
			{
				if (m_repository.Delete(user.UserID))
				{
					DeleteUserRelation((int)user.UserID, user.UserName);
					result = uow.Commit();
				}
			}
			return result;
		}
		/// <summary>
		/// 批量删除用户及相关权限
		/// </summary>
		/// <param name="ids"></param>
		public bool BatchDel(string ids)
		{
			if (!DataValidator.IsValidId(ids))
			{
				return false;
			}
			bool result = true;
			foreach (string id in ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
			{
				if(!DelUserFull(id.ToInt32()))
				{
					result = false;
					break;
				}
			}
			return result;
		}
		/// <summary>
		/// 删除用户相关信息。
		/// 1、字段权限（FieldPermissions）。
		/// 2、节点权限（NodePermissions）。
		/// 3、专题权限（SpecialPermissions）。
		/// 4、会员有效期兑换日志（UserValidLog）。
		/// 5、会员点券兑换日志（UserPointLog）。
		/// 6、会员积分兑换日志（UserExpLog）。
		/// 7、联系人相关信息（Contacter、U_UserText、ClientLog、RemindItem）。
		/// 8、收藏夹信息。
		/// 9、会员添加的好友信息和被别人添加为好友的信息。
		/// </summary>
		/// <param name="id"></param>
		/// <param name="userName"></param>
		public void DeleteUserRelation(int id, string userName)
		{
			_userGroupsServiceApp.DeleteFieldPermissionFromGroup(id, 0);
			_userGroupsServiceApp.DeleteNodePermissionFromGroup(groupID: id, idType: 0);
			_userGroupsServiceApp.DeleteSpecialPermissionFromGroup(groupID:id, idType: 0);
			_validLogRepository.Delete(p=>p.UserName == userName);
			_pointLogRepository.Delete(p => p.UserName == userName);
			_expLogRepository.Delete(p => p.UserName == userName);
			_contacterRepository.DeleteByUserName(userName);
			_favoriteRepository.Delete(p => p.UserID == id);
			_friendRepository.Delete(p=>p.UserName == userName);
			_friendRepository.Delete(p => p.FriendName == userName);
		}
		#endregion

		#region 修改会员
		/// <summary>
		/// 修改会员、联系人、联系人扩展。
		/// 1、修改会员。
		/// 2、修改联系人。
		/// 3、修改联系人扩展。
		/// </summary>
		/// <param name="usersInfo"></param>
		/// <param name="contacterInfo"></param>
		/// <returns></returns>
		public bool UpdateUserFull(UsersEntity usersInfo, ContacterEntity contacterInfo)
		{
			bool result = false;
			if (m_repository.Update(usersInfo))
			{
				contacterInfo.ClientID = usersInfo.ClientID;
				if (usersInfo.UserType == (int)UserTypeEnum.Persional)
				{
					contacterInfo.UserType = (int)ContacterType.Persional;
				}
				else
				{
					contacterInfo.UserType = (int)ContacterType.EnterpriceMainContacter;
				}
				result = SaveContacter(contacterInfo);
			}
			return result;
		}
		/// <summary>
		/// 修改会员、联系人、联系人扩展。
		/// 1、修改会员。
		/// 2、修改联系人。
		/// 3、修改联系人扩展。
		/// </summary>
		/// <param name="usersInfo"></param>
		/// <param name="contacterInfo"></param>
		/// <returns></returns>
		public async Task<bool> UpdateUserFullAsync(UsersEntity usersInfo, ContacterEntity contacterInfo)
		{
			bool result = false;
			if (await m_repository.UpdateAsync(usersInfo))
			{
				contacterInfo.ClientID = usersInfo.ClientID;
				if (usersInfo.UserType == (int)UserTypeEnum.Persional)
				{
					contacterInfo.UserType = (int)ContacterType.Persional;
				}
				else
				{
					contacterInfo.UserType = (int)ContacterType.EnterpriceMainContacter;
				}
				result = SaveContacter(contacterInfo);
			}
			return result;
		}
		#endregion

		#region 会员激励
		/// <summary>
		/// 会员激励
		/// </summary>
		/// <param name="eType">激励类型：0：资金；1：积分；2：点券；3：有效期；</param>
		/// <param name="eAction">激励方向：Add：增加；Minus：减少；</param>
		/// <param name="idType">ID类型：0：所有会员；1：会员ID；2：会员名；3：会员组；</param>
		/// <param name="ids">会员ID或会员名或会员组ID</param>
		/// <param name="howMany">激励数量</param>
		/// <param name="remark">备注</param>
		/// <param name="memo">内部记录</param>
		/// <returns></returns>
		public bool UserEncourageStrategy(int eType, string eAction, int idType, string ids, int howMany, string remark = "", string memo = "")
		{
			bool result = false;
			howMany = (string.Compare(eAction, "Minus", StringComparison.OrdinalIgnoreCase) == 0) ? -Math.Abs(howMany) : Math.Abs(howMany);
			switch (eType)
			{
				case 0:
					if (idType == 0)
					{
						result = _userMoneyServiceApp.IncreaseForAll(howMany.ToDecimal(), remark, memo);
					}
					else if (idType == 1)
					{
						result = _userMoneyServiceApp.IncreaseForUserID(ids, howMany.ToDecimal(), remark, memo);
					}
					else if (idType == 2)
					{
						result = _userMoneyServiceApp.IncreaseForUsers(ids, howMany.ToDecimal(), remark, memo);
					}
					else if (idType == 3)
					{
						result = _userMoneyServiceApp.IncreaseForGroup(ids, howMany.ToDecimal(), remark, memo);
					}
					break;
				case 1:
					if (idType == 0)
					{
						result = _userExpServiceApp.IncreaseForAll(howMany, remark, memo);
					}
					else if (idType == 1)
					{
						result = _userExpServiceApp.IncreaseForUserID(ids, howMany, remark, memo);
					}
					else if (idType == 2)
					{
						result = _userExpServiceApp.IncreaseForUsers(ids, howMany, remark, memo);
					}
					else if (idType == 3)
					{
						result = _userExpServiceApp.IncreaseForGroup(ids, howMany, remark, memo);
					}
					break;
				case 2:
					if (idType == 0)
					{
						result = _userPointServiceApp.IncreaseForAll(howMany, remark, memo);
					}
					else if (idType == 1)
					{
						result = _userPointServiceApp.IncreaseForUserID(ids, howMany, remark, memo);
					}
					else if (idType == 2)
					{
						result = _userPointServiceApp.IncreaseForUsers(ids, howMany, remark, memo);
					}
					else if (idType == 3)
					{
						result = _userPointServiceApp.IncreaseForGroup(ids, howMany, remark, memo);
					}
					break;
				case 3:
					if (idType == 0)
					{
						result = _userValidDateServiceApp.IncreaseForAll(howMany, remark, memo);
					}
					else if (idType == 1)
					{
						result = _userValidDateServiceApp.IncreaseForUserID(ids, howMany, remark, memo);
					}
					else if (idType == 2)
					{
						result = _userValidDateServiceApp.IncreaseForUsers(ids, howMany, remark, memo);
					}
					else if (idType == 3)
					{
						result = _userValidDateServiceApp.IncreaseForGroup(ids, howMany, remark, memo);
					}
					break;
			}
			return result;
		}
		/// <summary>
		/// 会员激励
		/// </summary>
		/// <param name="eType">激励类型：0：资金；1：积分；2：点券；3：有效期；</param>
		/// <param name="eAction">激励方向：Add：增加；Minus：减少；</param>
		/// <param name="idType">ID类型：0：所有会员；1：会员ID；2：会员名；3：会员组；</param>
		/// <param name="ids">会员ID或会员名或会员组ID</param>
		/// <param name="howMany">激励数量</param>
		/// <param name="remark">备注</param>
		/// <param name="memo">内部记录</param>
		/// <returns></returns>
		public bool UserEncourageStrategy(int eType, string eAction, int idType, string ids, decimal howMany, string remark = "", string memo = "")
		{
			bool result = false;
			howMany = (string.Compare(eAction, "Minus", StringComparison.OrdinalIgnoreCase) == 0) ? -Math.Abs(howMany) : Math.Abs(howMany);
			switch (eType)
			{
				case 0:
					if (idType == 0)
					{
						result = _userMoneyServiceApp.IncreaseForAll(howMany, remark, memo);
					}
					else if (idType == 1)
					{
						result = _userMoneyServiceApp.IncreaseForUserID(ids, howMany, remark, memo);
					}
					else if (idType == 2)
					{
						result = _userMoneyServiceApp.IncreaseForUsers(ids, howMany, remark, memo);
					}
					else if (idType == 3)
					{
						result = _userMoneyServiceApp.IncreaseForGroup(ids, howMany, remark, memo);
					}
					break;
				case 1:
					if (idType == 0)
					{
						result = _userExpServiceApp.IncreaseForAll((int)howMany, remark, memo);
					}
					else if (idType == 1)
					{
						result = _userExpServiceApp.IncreaseForUserID(ids, (int)howMany, remark, memo);
					}
					else if (idType == 2)
					{
						result = _userExpServiceApp.IncreaseForUsers(ids, (int)howMany, remark, memo);
					}
					else if (idType == 3)
					{
						result = _userExpServiceApp.IncreaseForGroup(ids, (int)howMany, remark, memo);
					}
					break;
				case 2:
					if (idType == 0)
					{
						result = _userPointServiceApp.IncreaseForAll((int)howMany, remark, memo);
					}
					else if (idType == 1)
					{
						result = _userPointServiceApp.IncreaseForUserID(ids, (int)howMany, remark, memo);
					}
					else if (idType == 2)
					{
						result = _userPointServiceApp.IncreaseForUsers(ids, (int)howMany, remark, memo);
					}
					else if (idType == 3)
					{
						result = _userPointServiceApp.IncreaseForGroup(ids, (int)howMany, remark, memo);
					}
					break;
				case 3:
					if (idType == 0)
					{
						result = _userValidDateServiceApp.IncreaseForAll((int)howMany, remark, memo);
					}
					else if (idType == 1)
					{
						result = _userValidDateServiceApp.IncreaseForUserID(ids, (int)howMany, remark, memo);
					}
					else if (idType == 2)
					{
						result = _userValidDateServiceApp.IncreaseForUsers(ids, (int)howMany, remark, memo);
					}
					else if (idType == 3)
					{
						result = _userValidDateServiceApp.IncreaseForGroup(ids, (int)howMany, remark, memo);
					}
					break;
			}
			return result;
		}

		/// <summary>
		/// 会员激励
		/// </summary>
		/// <param name="eType">激励类型：0：资金；1：积分；2：点券；3：有效期；</param>
		/// <param name="eAction">激励方向：Add：增加；Minus：减少；</param>
		/// <param name="idType">ID类型：0：所有会员；1：会员ID；2：会员名；3：会员组；</param>
		/// <param name="ids">会员ID或会员名或会员组ID</param>
		/// <param name="howMany">激励数量</param>
		/// <param name="remark">备注</param>
		/// <param name="memo">内部记录</param>
		/// <returns></returns>
		public async Task<bool> UserEncourageStrategyAsync(int eType, string eAction, int idType, string ids, int howMany, string remark = "", string memo = "")
		{
			bool result = false;
			howMany = (string.Compare(eAction, "Minus", StringComparison.OrdinalIgnoreCase) == 0) ? -Math.Abs(howMany) : Math.Abs(howMany);
			switch (eType)
			{
				case 0:
					if (idType == 0)
					{
						result = await _userMoneyServiceApp.IncreaseForAllAsync(howMany.ToDecimal(), remark, memo);
					}
					else if (idType == 1)
					{
						result = await _userMoneyServiceApp.IncreaseForUserIDAsync(ids, howMany.ToDecimal(), remark, memo);
					}
					else if (idType == 2)
					{
						result = await _userMoneyServiceApp.IncreaseForUsersAsync(ids, howMany.ToDecimal(), remark, memo);
					}
					else if (idType == 3)
					{
						result = await _userMoneyServiceApp.IncreaseForGroupAsync(ids, howMany.ToDecimal(), remark, memo);
					}
					break;
				case 1:
					if (idType == 0)
					{
						result = await _userExpServiceApp.IncreaseForAllAsync(howMany, remark, memo);
					}
					else if (idType == 1)
					{
						result = await _userExpServiceApp.IncreaseForUserIDAsync(ids, howMany, remark, memo);
					}
					else if (idType == 2)
					{
						result = await _userExpServiceApp.IncreaseForUsersAsync(ids, howMany, remark, memo);
					}
					else if (idType == 3)
					{
						result = await _userExpServiceApp.IncreaseForGroupAsync(ids, howMany, remark, memo);
					}
					break;
				case 2:
					if (idType == 0)
					{
						result = await _userPointServiceApp.IncreaseForAllAsync(howMany, remark, memo);
					}
					else if (idType == 1)
					{
						result = await _userPointServiceApp.IncreaseForUserIDAsync(ids, howMany, remark, memo);
					}
					else if (idType == 2)
					{
						result = await _userPointServiceApp.IncreaseForUsersAsync(ids, howMany, remark, memo);
					}
					else if (idType == 3)
					{
						result = await _userPointServiceApp.IncreaseForGroupAsync(ids, howMany, remark, memo);
					}
					break;
				case 3:
					if (idType == 0)
					{
						result = await _userValidDateServiceApp.IncreaseForAllAsync(howMany, remark, memo);
					}
					else if (idType == 1)
					{
						result = await _userValidDateServiceApp.IncreaseForUserIDAsync(ids, howMany, remark, memo);
					}
					else if (idType == 2)
					{
						result = await _userValidDateServiceApp.IncreaseForUsersAsync(ids, howMany, remark, memo);
					}
					else if (idType == 3)
					{
						result = await _userValidDateServiceApp.IncreaseForGroupAsync(ids, howMany, remark, memo);
					}
					break;
			}
			return result;
		}
		/// <summary>
		/// 会员激励
		/// </summary>
		/// <param name="eType">激励类型：0：资金；1：积分；2：点券；3：有效期；</param>
		/// <param name="eAction">激励方向：Add：增加；Minus：减少；</param>
		/// <param name="idType">ID类型：0：所有会员；1：会员ID；2：会员名；3：会员组；</param>
		/// <param name="ids">会员ID或会员名或会员组ID</param>
		/// <param name="howMany">激励数量</param>
		/// <param name="remark">备注</param>
		/// <param name="memo">内部记录</param>
		/// <returns></returns>
		public async Task<bool> UserEncourageStrategyAsync(int eType, string eAction, int idType, string ids, decimal howMany, string remark = "", string memo = "")
		{
			bool result = false;
			howMany = (string.Compare(eAction, "Minus", StringComparison.OrdinalIgnoreCase) == 0) ? -Math.Abs(howMany) : Math.Abs(howMany);
			switch (eType)
			{
				case 0:
					if (idType == 0)
					{
						result = await _userMoneyServiceApp.IncreaseForAllAsync(howMany, remark, memo);
					}
					else if (idType == 1)
					{
						result = await _userMoneyServiceApp.IncreaseForUserIDAsync(ids, howMany, remark, memo);
					}
					else if (idType == 2)
					{
						result = await _userMoneyServiceApp.IncreaseForUsersAsync(ids, howMany, remark, memo);
					}
					else if (idType == 3)
					{
						result = await _userMoneyServiceApp.IncreaseForGroupAsync(ids, howMany, remark, memo);
					}
					break;
				case 1:
					if (idType == 0)
					{
						result = await _userExpServiceApp.IncreaseForAllAsync((int)howMany, remark, memo);
					}
					else if (idType == 1)
					{
						result = await _userExpServiceApp.IncreaseForUserIDAsync(ids, (int)howMany, remark, memo);
					}
					else if (idType == 2)
					{
						result = await _userExpServiceApp.IncreaseForUsersAsync(ids, (int)howMany, remark, memo);
					}
					else if (idType == 3)
					{
						result = await _userExpServiceApp.IncreaseForGroupAsync(ids, (int)howMany, remark, memo);
					}
					break;
				case 2:
					if (idType == 0)
					{
						result = await _userPointServiceApp.IncreaseForAllAsync((int)howMany, remark, memo);
					}
					else if (idType == 1)
					{
						result = await _userPointServiceApp.IncreaseForUserIDAsync(ids, (int)howMany, remark, memo);
					}
					else if (idType == 2)
					{
						result = await _userPointServiceApp.IncreaseForUsersAsync(ids, (int)howMany, remark, memo);
					}
					else if (idType == 3)
					{
						result = await _userPointServiceApp.IncreaseForGroupAsync(ids, (int)howMany, remark, memo);
					}
					break;
				case 3:
					if (idType == 0)
					{
						result = await _userValidDateServiceApp.IncreaseForAllAsync((int)howMany, remark, memo);
					}
					else if (idType == 1)
					{
						result = await _userValidDateServiceApp.IncreaseForUserIDAsync(ids, (int)howMany, remark, memo);
					}
					else if (idType == 2)
					{
						result = await _userValidDateServiceApp.IncreaseForUsersAsync(ids, (int)howMany, remark, memo);
					}
					else if (idType == 3)
					{
						result = await _userValidDateServiceApp.IncreaseForGroupAsync(ids, (int)howMany, remark, memo);
					}
					break;
			}
			return result;
		}
		#endregion

		#region 会员升级为企业会员
		/// <summary>
		/// 会员升级为企业会员
		/// </summary>
		/// <param name="companyId"></param>
		/// <param name="userId"></param>
		/// <param name="userType"></param>
		/// <param name="companyClientId"></param>
		/// <returns></returns>
		public bool UpdateForCompany(int companyId, int userId, int userType, int companyClientId)
		{
			string strColumns = "UserType = @UserType, CompanyID = @CompanyID ";
			string strWhere = "UserID = @UserID";
			var parameters = new DynamicParameters();
			parameters.Add("UserType", userType);
			parameters.Add("CompanyID", companyId);
			parameters.Add("UserID", userId);
			if (companyClientId > 0)
			{
				strColumns += ", ClientID = @ClientID";
				parameters.Add("ClientID", companyClientId);
			}
			return m_repository.Update(strColumns, strWhere, parameters);
		}
		/// <summary>
		/// 会员升级为企业会员
		/// </summary>
		/// <param name="companyId"></param>
		/// <param name="userId"></param>
		/// <param name="userType"></param>
		/// <param name="companyClientId"></param>
		/// <returns></returns>
		public async Task<bool> UpdateForCompanyAsync(int companyId, int userId, int userType, int companyClientId)
		{
			string strColumns = "UserType = @UserType, CompanyID = @CompanyID ";
			string strWhere = "UserID = @UserID";
			var parameters = new DynamicParameters();
			parameters.Add("UserType", userType);
			parameters.Add("CompanyID", companyId);
			parameters.Add("UserID", userId);
			if (companyClientId > 0)
			{
				strColumns += ", ClientID = @ClientID";
				parameters.Add("ClientID", companyClientId);
			}
			return await m_repository.UpdateAsync(strColumns, strWhere, parameters);
		}
		#endregion

		#region 商户成员管理
		/// <summary>
		/// 从商户中移除
		/// </summary>
		/// <param name="UserName"></param>
		/// <returns></returns>
		public bool RemoveFromCompany(string UserName)
		{
			string strColumns = "UserType = 0, CompanyID = 0, ClientID = 0";
			string strWhere = "UserType > 1 AND UserName = @UserName";
			var parameters = new DynamicParameters();
			parameters.Add("UserName", UserName);
			return m_repository.Update(strColumns, strWhere, parameters);
		}
		/// <summary>
		/// 从商户中移除
		/// </summary>
		/// <param name="UserName"></param>
		/// <returns></returns>
		public async Task<bool> RemoveFromCompanyAsync(string UserName)
		{
			string strColumns = "UserType = 0, CompanyID = 0, ClientID = 0";
			string strWhere = "UserType > 1 AND UserName = @UserName";
			var parameters = new DynamicParameters();
			parameters.Add("UserName", UserName);
			return await m_repository.UpdateAsync(strColumns, strWhere, parameters);
		}

		/// <summary>
		/// 升级为商户管理员
		/// </summary>
		/// <param name="UserName"></param>
		/// <returns></returns>
		public bool AddToCompanyAdmin(string UserName)
		{
			string strColumns = "UserType = 2";
			string strWhere = "UserType > 2 AND UserName = @UserName";
			var parameters = new DynamicParameters();
			parameters.Add("UserName", UserName);
			return m_repository.Update(strColumns, strWhere, parameters);
		}
		/// <summary>
		/// 升级为商户管理员
		/// </summary>
		/// <param name="UserName"></param>
		/// <returns></returns>
		public async Task<bool> AddToCompanyAdminAsync(string UserName)
		{
			string strColumns = "UserType = 2";
			string strWhere = "UserType > 2 AND UserName = @UserName";
			var parameters = new DynamicParameters();
			parameters.Add("UserName", UserName);
			return await m_repository.UpdateAsync(strColumns, strWhere, parameters);
		}

		/// <summary>
		/// 降级为商户的普通成员
		/// </summary>
		/// <param name="UserName"></param>
		/// <returns></returns>
		public bool RemoveFromCompanyAdmin(string UserName)
		{
			string strColumns = "UserType = 3";
			string strWhere = "UserType = 2 AND UserName = @UserName";
			var parameters = new DynamicParameters();
			parameters.Add("UserName", UserName);
			return m_repository.Update(strColumns, strWhere, parameters);
		}
		/// <summary>
		/// 降级为商户的普通成员
		/// </summary>
		/// <param name="UserName"></param>
		/// <returns></returns>
		public async Task<bool> RemoveFromCompanyAdminAsync(string UserName)
		{
			string strColumns = "UserType = 3";
			string strWhere = "UserType = 2 AND UserName = @UserName";
			var parameters = new DynamicParameters();
			parameters.Add("UserName", UserName);
			return await m_repository.UpdateAsync(strColumns, strWhere, parameters);
		}

		/// <summary>
		/// 允许待审核用户成为商户的正式成员
		/// </summary>
		/// <param name="UserName"></param>
		/// <param name="companyClientId"></param>
		/// <returns></returns>
		public bool AgreeJoinCompany(string UserName, int companyClientId)
		{
			string strColumns = "UserType = 3";
			string strWhere = "UserType = 4 AND UserName = @UserName";
			var parameters = new DynamicParameters();
			parameters.Add("UserName", UserName);
			if (companyClientId > 0)
			{
				strColumns += ", ClientID = @ClientID";
				parameters.Add("ClientID", companyClientId);
			}
			return m_repository.Update(strColumns, strWhere, parameters);
		}
		/// <summary>
		/// 允许待审核用户成为商户的正式成员
		/// </summary>
		/// <param name="UserName"></param>
		/// <param name="companyClientId"></param>
		/// <returns></returns>
		public async Task<bool> AgreeJoinCompanyAsync(string UserName, int companyClientId)
		{
			string strColumns = "UserType = 3";
			string strWhere = "UserType = 4 AND UserName = @UserName";
			var parameters = new DynamicParameters();
			parameters.Add("UserName", UserName);
			if (companyClientId > 0)
			{
				strColumns += ", ClientID = @ClientID";
				parameters.Add("ClientID", companyClientId);
			}
			return await m_repository.UpdateAsync(strColumns, strWhere, parameters);
		}
		#endregion

		#region 辅助方法
		/// <summary>
		/// 通过实体类生成会员对应的ClaimsPrincipal对像
		/// </summary>
		/// <param name="entity"></param>
		/// <returns></returns>
		public ClaimsPrincipal CreateClaimsIdentity(UsersEntity entity)
		{
			var claims = new List<Claim>()
			{
				new Claim(ClaimTypes.Sid,entity.UserID.ToString())
				,new Claim(ClaimTypes.Name,entity.UserName)
				,new Claim("GroupID",entity.GroupID.ToString())
				,new Claim("CompanyID",entity.CompanyID.ToString())
				,new Claim("ClientID",entity.ClientID.ToString())
				,new Claim("UserType",entity.UserType.ToString())
				,new Claim("TrueName",entity.TrueName.ToString())
				,new Claim("TrueName",entity.TrueName.ToString())
				,new Claim("Email",entity.Email.ToString())
				,new Claim("Mobile",entity.Mobile.ToString())
				,new Claim("UserFace",entity.UserFace)
				,new Claim("LoginIP",entity.LoginIP)
				,new Claim("LoginTime",entity.LoginTime.HasValue?entity.LoginTime.Value.ToString("yyyy-MM-dd HH:mm:ss"):"")
				,new Claim("IsInheritGroupRole",entity.IsInheritGroupRole.ToString())
				,new Claim("IdByIdType",entity.IdByIdType.ToString())
			};
			var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
			return new ClaimsPrincipal(claimsIdentity);
		}
		/// <summary>
		/// 保存联系人信息：如果存在相同会员名的联系人则更新
		/// </summary>
		/// <param name="contacterInfo"></param>
		/// <returns></returns>
		private bool SaveContacter(ContacterEntity contacterInfo)
		{
			bool result = false;
			if (_contacterRepository.IsExist(p=>p.UserName == contacterInfo.UserName))
			{
				var oldContacterInfo = _contacterRepository.Get(p => p.UserName == contacterInfo.UserName);
				contacterInfo.ContacterID = oldContacterInfo.ContacterID;
				result = _contacterRepository.Update(contacterInfo);
				if (result)
				{
					_contacterRepository.UpdateDataOption(_ModelsServiceApp.GetModelByModelType(ModelType.UserOption).TableName, contacterInfo);
				}
			}
			else
			{
				result = _contacterRepository.Add(contacterInfo);
				if (result)
				{
					_contacterRepository.AddDataOption(_ModelsServiceApp.GetModelByModelType(ModelType.UserOption).TableName, contacterInfo);
				}
			}
			return result;
		}
		#endregion
	}
}
